package com.taobao.ued.toy.web;


import com.taobao.cms.biz.ao.PhotoAO;
import com.taobao.session.SessionKeyConstants;
import com.taobao.ued.toy.domain.Designer;
import com.taobao.ued.toy.domain.Pic;
import com.taobao.ued.toy.domain.ToyConfig;
import com.taobao.ued.toy.service.ToyManager;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;

@Controller
public class PicController {

	@Autowired
	private ToyManager toyManager;

	@Resource
	private ToyConfig toyConfig;

	@Resource
	private PhotoAO photoAO;

	@RequestMapping(value = "/secure/{workId}/pics/add", method = RequestMethod.GET)
	public String addPic(@PathVariable int workId,
						 HttpServletRequest request,
						 Model model) {
		model.addAttribute("contextpath", request.getContextPath());
		model.addAttribute("workId", workId);
		return "pic_upload";
	}


	@RequestMapping(value = "/secure/{workId}/pics/doAdd", method = RequestMethod.POST)
	public void doAddPic(
			@ModelAttribute Pic pic,
			@PathVariable int workId,
			@RequestParam MultipartFile urlFile,
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response) throws Exception {
		String id = (String) session.getAttribute(SessionKeyConstants.ATTRIBUTE_USER_ID);

		if (id == null) {
			response.sendRedirect(toyConfig.getLoginUrl() + URLEncoder.encode("http://" + request.getServerName() +
					request.getContextPath() + "/secure/" + workId + "/pics/add"));
			return;
		}

		Designer d = toyManager.getDesigner(id);

		pic.setWorkId(workId);
		if (urlFile.getSize() > 0) {
			String json = photoAO.upladFile(d.getName(),
					urlFile.getOriginalFilename(),
					urlFile.getContentType(),
					urlFile.getBytes());
			JSONObject jsonObject = JSONObject.fromObject(json);
			pic.setUrl((String) jsonObject.get("url"));
		}
		toyManager.addPic(pic);
		response.sendRedirect(request.getContextPath() + "/secure/"
				+ workId + "/pics/add");
	}
}
